package com.blogspot.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.blogspot.dao.BlogspotDao;
import com.blogspot.domain.TestTable;

@Repository
public class BlogspotDaoImpl implements BlogspotDao , Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
//    EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistentUnit");  
//    EntityManager em = emf.createEntityManager();  
//	

    @PersistenceContext
    EntityManager em;
    
    protected HibernateTemplate template;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory)
    {
      template = new HibernateTemplate(sessionFactory);
    }
	
	public EntityManager getEntityManager() {
		// TODO Auto-generated method stub
		return em;
	}
	
    
    @SuppressWarnings("unchecked")
	public List<Object[]> querySql(String sql, List<String> params) {
        Query query = em.createNativeQuery(sql);
        
        for (int i = 0 ; i < params.size() ; i++) {
            query.setParameter(i + 1, params.get(i));
        }
        
        return (List<Object[]>)query.getResultList();
    }
	
    public void save() {
    	em.persist(null);
    }
    
    @SuppressWarnings("unchecked")
	public TestTable getTestTable(TestTable obj) {
//    	TestTable t = new TestTable();
//    	t.setName("AAA");
//    	t.setAddress("bbb");
//    	template.persist(t);
//    	em.persist(t);
    	//return (TestTable) em.createQuery("select p from TestTable p ",TestTable.class).getResultList().get(0);
    	return ((List<TestTable>) template.find("select p from TestTable p")).get(0);
                //.getResultList();
    }

}
